import { Toast } from 'antd-mobile'
import axios from 'axios'

const instance = axios.create({
  baseURL: import.meta.env.VITE_NODE_FLAG === 'prod' ? import.meta.env.VITE_API_URL : 'api',
  // 指定请求超时的毫秒数
  timeout: 20000,
  // 表示跨域请求时是否需要使用凭证
  withCredentials: false,
  headers: {
  },
})

// 前置拦截器（发起请求之前的拦截）
instance.interceptors.request.use(
  (config: any) => {
    if (config?.showLoading) {
      Toast.show({
        icon: 'loading',
        content: '加载中…',
        maskClickable: false,
        duration: 0,
      })
    }

    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 后置拦截器（获取到响应时的拦截）
instance.interceptors.response.use(
  (response: any) => {
    Toast.clear()
    return response
  },
  (error) => {
    const { response } = error
    Toast.show('网络异常,请重试!')
    if (response && response.data) {
      return Promise.reject(error)
    }
    const { message } = error
    console.error(message)
    return Promise.reject(error)
  }
)

// 导出常用函数

/**
 * @param {string} url
 * @param {object} data
 * @param {object} params
 */
export function post(url: string, data = {}, options = {}) {
  return instance({
    method: 'post',
    url,
    data,
    ...options,
  })
}

export function postBlob(url: string, data = {}, params = {}, options = {}) {
  return instance({
    method: 'post',
    url,
    data,
    params,
    responseType: 'blob',
    ...options,
  })
}

/**
 * @param {string} url
 * @param {object} params
 */
export function get(url: string, params = {}, options = {}) {
  return instance({
    method: 'get',
    url,
    params,
    ...options,
  })
}

/**
 * @param {string} url
 * @param {object} data
 * @param {object} params
 */
export function put(url: string, data = {}, params = {}, options = {}) {
  return instance({
    method: 'put',
    url,
    params,
    data,
    ...options,
  })
}

/**
 * @param {string} url
 * @param {object} params
 */
export function _delete(url: string, params = {}, options = {}) {
  return instance({
    method: 'delete',
    url,
    params,
    ...options,
  })
}

export default instance
